package com.tan.lbs.service.impl;

import java.util.ArrayList;

import com.tan.lbs.dao.ItemDAO;
import com.tan.lbs.dao.LocationDAO;
import com.tan.lbs.dao.MediaDAO;
import com.tan.lbs.dao.impl.ItemDAOImpl;
import com.tan.lbs.dao.impl.LocationDAOImpl;
import com.tan.lbs.dao.impl.MediaDAOImpl;
import com.tan.lbs.entity.Item;
import com.tan.lbs.entity.ItemHeader;
import com.tan.lbs.entity.Location;
import com.tan.lbs.service.ItemService;

public class ItemServiceImpl implements ItemService {
	
	private ItemDAO itemDAO;
	private LocationDAO locationDAO;
	private MediaDAO mediaDAO;
	
	public ItemServiceImpl() {
		itemDAO = new ItemDAOImpl();
		locationDAO = new LocationDAOImpl();
		mediaDAO = new MediaDAOImpl();
	}

	@Override
	public String createItemWithoutLocation(Item item) {
		return itemDAO.create(item);
	}

	@Override
	public void modifyItemWithoutLocation(Item item) {
		Item oldItem  = itemDAO.readByID(item.getItemID());
		item.setLocationID(oldItem.getLocationID());
		item.setIconID(oldItem.getIconID());
		item.setContainedMediaID(oldItem.getContainedMediaID());
		itemDAO.update(item);
	}

	@Override
	public Item readItemDetails(String itemID) {
		return itemDAO.readByID(itemID);
	}

	@Override
	public String createLocation(Location location,String itemID) {
		Item item = itemDAO.readByID(itemID);
		String locationID = locationDAO.create(location);
		item.setLocationID(locationID);
		itemDAO.update(item);
		return locationID;
	}

	@Override
	public ArrayList<ItemHeader> retrieveItemList(String gameID) {
		ArrayList<Item> items = itemDAO.searchByGame(gameID);
		ArrayList<ItemHeader> headers = new ArrayList<ItemHeader>();
		for(Item item : items) {
			ItemHeader header = new ItemHeader();
			if(item.getLocationID()!=null) {
				header.setLocation(locationDAO.readByID(item.getLocationID()));
			}
			header.setItemID(item.getItemID());
			header.setItemTitle(item.getTitle());
			headers.add(header);
		}
		return headers;
	}

	@Override
	public void deleteLocation(String itemID, String locationID) {
		Item item = itemDAO.readByID(itemID);
		item.setLocationID(null);
		itemDAO.update(item);
		locationDAO.delete(locationID);
	}

	@Override
	public void deleteItemAndLocation(String itemID) {
		String locationID = itemDAO.readByID(itemID).getLocationID();
		String iconID = itemDAO.readByID(itemID).getIconID();
		String mediaID = itemDAO.readByID(itemID).getContainedMediaID();
		itemDAO.delete(itemID);
		locationDAO.delete(locationID);
		mediaDAO.delete(iconID);
		mediaDAO.delete(mediaID);
	}

}
